package cn.liwq.demo.java.nio;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author liwq
 * @version 1.0
 * @date 2018-07-31 20:27:11
 */
public class BufferDemo {

    public static void main(String[] args) throws IOException {
        RandomAccessFile aFile = new RandomAccessFile(
                (new BufferDemo()).getClass().getClassLoader().getResource("").getPath() + "data/nio-data.txt", "rw");
        FileChannel inChannel = aFile.getChannel();

        //create buffer with capacity of 48 bytes
        ByteBuffer buf = ByteBuffer.allocate(48);
        System.out.println("position : " + buf.position());
        System.out.println("limit : " + buf.limit());
        //read into buffer.
        int bytesRead = inChannel.read(buf);
        System.out.println("position : " + buf.position());
        System.out.println("limit : " + buf.limit());
        while (bytesRead != -1) {
            //make buffer ready for read
            buf.flip();

            while (buf.hasRemaining()) {
                // read 1 byte at a time
                System.out.print((char) buf.get());
            }

            //make buffer ready for writing
            buf.clear();
            bytesRead = inChannel.read(buf);
        }
        aFile.close();
    }
}
